package com.gollum.web.security.handler;

import com.alibaba.fastjson2.JSON;
import com.gollum.common.domain.response.RestResponse;
import com.gollum.common.utils.ServletUtils;
import com.gollum.system.domain.response.LoginUser;
import com.gollum.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义退出处理类
 * @author Herther
 * @version 1.0.0
 * @createTime 2022年08月25日 23:12:00
 */
@Configuration
public class LogoutSuccessHandler implements org.springframework.security.web.authentication.logout.LogoutSuccessHandler {

    @Autowired
    protected TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser)){

            String username = loginUser.getUsername();
            //redis中删除
            tokenService.removeLoginUser(loginUser.getToken());
            //记录退出登录日志
            // TODO: 2022/8/25  后期需要新增退出登录日志
        }
        String resultStr = JSON.toJSONString(RestResponse.success("退出成功"));
        //响应前端
        ServletUtils.renderString(response,resultStr);
    }
}
